<template>
  <ModalLayout>
    <div>
      <ModalHeader :icon="NewFileSVG" title="权限管理"></ModalHeader>
      <div class="vuefinder__new-file-modal__content">
        <a-tabs v-model:activeKey="activeKey" :tabBarStyle="{ border: 'none' }">
          <a-tab-pane key="inside" tab="内部权限">
            <div class="h-[400px] overflow-y-auto">
              <div
                class="flex justify-between h-[32px] leading-[32px] mb-[8px]"
                v-for="(item, index) in permissionList"
                :key="item.id"
              >
                <div>{{ item.name }}</div>
                <a-dropdown
                  placement="bottomRight"
                  :trigger="['click']"
                  @openChange="setCurrent(item)"
                >
                  <div
                    class="flex items-center cursor-pointer hover:text-primary-6 px-[10px]"
                  >
                    <span>{{
                      roleList.find((n) => n.id === item.role_id)?.['role_name']
                    }}</span>
                    <span class="iconfont icon-Down pl-[4px] text-xs"></span>
                  </div>
                  <template #overlay>
                    <a-menu v-model:selectedKeys="current">
                      <a-menu-item
                        style="min-width: 200px"
                        v-for="roleItem in roleList"
                        :key="roleItem.key"
                        :disabled="app.requestParams.employee_id === item.id"
                        @click="menuHandle(roleItem, index)"
                      >
                        <div class="menu-item">
                          <span
                            class="menu-title"
                            :class="[
                              roleItem.key === 'del'
                                ? 'menu-title-del'
                                : '',
                            ]"
                            >{{ roleItem.role_name }}</span
                          >
                          <span class="menu-desc">{{ roleItem.desc }}</span>
                        </div>
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </div>
            </div>
          </a-tab-pane>
          <a-tab-pane key="outside" tab="外部权限">
            <div class="h-[400px] overflow-y-auto">
              <div
                class="flex items-center mb-[24px]"
                v-for="item in outSidePermissionList"
                :key="item.id"
              >
                <span class="pr-[12px]">{{ item.name }}</span>
                <a-select
                  class="flex-1"
                  mode="multiple"
                  :fieldNames="{ value: 'id', label: 'params_content' }"
                  :options="item.options"
                  v-model:value="item.selectKeys"
                />
              </div>
            </div>
          </a-tab-pane>
          <template #rightExtra v-if="activeKey === 'inside'">
            <div
              class="flex items-center cursor-pointer border border-dashed text-neutral-6 border-neutral-6 hover:text-primary-6 hover:border-primary-6 rounded-md px-[8px] py-[4px]"
              @click="userSelectModal"
            >
              <span class="iconfont icon-TX-add pr-1"></span>
              <span>添加人员</span>
            </div>
          </template>
        </a-tabs>
      </div>
    </div>
    <template v-slot:buttons>
      <button
        type="button"
        @click="save"
        class="vf-btn vf-btn-primary bg-primary-6"
      >
        保存
      </button>
      <button
        type="button"
        @click="app.modal.close()"
        class="vf-btn vf-btn-secondary"
      >
        {{ t('Cancel') }}
      </button>
    </template>
    <ModalUserSelect
      ref="userSelectRef"
      :list="userList"
      @confirm="userConfirm"
    />
  </ModalLayout>
</template>

<script setup>
import ModalUserSelect from './ModalUserSelect.vue'
import ModalLayout from './ModalLayout.vue'
import { inject, ref, onMounted } from 'vue'
import { message } from 'ant-design-vue';
import ModalHeader from './ModalHeader.vue'
import NewFileSVG from '../icons/new_file.svg'

const app = inject('ServiceContainer')
const { t } = app.i18n
const userSelectRef = ref(null)
const permissionList = ref([])
const activeKey = ref('inside')
const current = ref(['edit'])
const roleList = ref([])
const userList = ref([])
const outSidePermissionList = ref([])
const setCurrent = (item) => {
  current.value = [roleList.value.find((n) => n.id === item.role_id)['key']]
}
// 菜单点击事件
const menuHandle = (authItem, index) => {
  if (authItem.key === 'remove') {
    permissionList.value.splice(index, 1)
    return false
  }
  permissionList.value[index]['role_id'] = authItem.id
}

// 添加人员
const userSelectModal = () => {
  userList.value = permissionList.value.map((item) => item.id)
  userSelectRef.value.open()
}

// 保存
const save = async () => {
  await Promise.all([saveInsidePermission(), saveOutsidePermission()])
  message.success('保存成功')
  app.modal.close()
}
// 保存内部数据
const saveInsidePermission = async () => {
  await app.requester.send({
    method: 'post',
    params: {
      fetchType: 'addpermission',
    },
    body: {
      project_id: app.requestParams.project_id,
      microdisk_id: app.modal.data.items[0].id,
      data: permissionList.value.map((item) => ({
        role_id: item.role_id,
        type_id: item?.type === 'department' ? 1 : 0,
        ...(item?.type === 'department' ? { department_id: item?.id } : { employee_id: item?.id }),
      }))
    },
  })
}

// 获取全部角色
const getRole = async () => {
  const { data } = await app.requester.send({
    url: '',
    method: 'get',
    params: {
      fetchType: 'getmicrodiskrole',
    },
  })
  roleList.value = [...data, { id: 0, role_name: '移除', key: 'del', desc: '' }]
}

// 根据微盘ID获取该微盘包含的会员权限
const getPermission = async () => {
  const { data } = await app.requester.send({
    url: '',
    method: 'get',
    params: {
      fetchType: 'getmicrodiskpermission',
      project_id: app.requestParams.project_id,
      microdisk_id: app.modal.data.items[0].id,
    },
  })
  permissionList.value = data
  userList.value = data.map((item) => item.id)
}

// 添加人员
const userConfirm = (data) => {
  permissionList.value = [
    ...permissionList.value,
    ...data
      .filter((item) => {
        return !permissionList.value.some((n) => n.id === item.id)
      })
      .map((item) => ({
        id: item.id,
        name: item.name,
        type: Reflect.has(item, 'employee_list') ? 'department' : 'employee',
        role_id: roleList.value.slice(-2, -1)[0]['id'],
      })),
  ]
}

// 获取外部权限
const getOutsidePermission = async () => {
  const { data } = await app.requester.send({
    url: '',
    method: 'get',
    params: {
      fetchType: 'getparambymicrodiskid',
      project_id: app.requestParams.project_id,
      md_id: app.modal.data.items[0].id,
    },
  })
  outSidePermissionList.value = data.map((item) => ({
    ...item,
    selectKeys: item.selectKeys ? item.selectKeys.split(',').map(Number) : [],
  }))
}

// 保存外部权限
const saveOutsidePermission = async () => {
  await app.requester.send({
    method: 'post',
    params: {
      fetchType: 'addparamspromission',
    },
    body: {
      md_id: app.modal.data.items[0].id,
      project_id: app.requestParams.project_id,
      params: outSidePermissionList.value.reduce((pre, v) => {
        if (v.selectKeys.length === 0) return pre
        pre[v.id] = v.selectKeys.join(',')
        return pre
      }, {}),
    },
  })
}

onMounted(() => {
  getRole()
  getPermission()
  getOutsidePermission()
})
</script>
<style scoped lang="scss">
:deep(.ant-dropdown-menu-item:hover) {
  @apply hover:bg-primary-1 hover:text-primary-6;
}
.menu-item {
  display: flex;
  flex-direction: column;
  @apply hover:text-primary-6;
  .menu-desc {
    @apply text-xs text-neutral-6;
  }
}
.menu-title-del{
  @apply text-red-500;
  @apply hover:text-red-500;

}
</style>
